package com.leo.tool.jdk.jdk4.bio;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

@Slf4j
public class Client {

    public static void main(String[] args) throws Exception {
        @Cleanup
        Socket socket = new Socket("localhost", 8000);
        send(socket);
        send(socket);
        bye(socket);
    }

    private static void send(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        outputStream.write("hello".getBytes());
        outputStream.flush();

        // 等待数据传输完成
        // 线程为RUNNING状态阻塞
        byte[] buff = new byte[1024];
        int len = inputStream.read(buff);
        log.info(new String(buff, 0, len));
    }

    private static void bye(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        outputStream.write("bye".getBytes());
        outputStream.flush();

        // 等待数据传输完成
        // 线程为RUNNING状态阻塞
        byte[] buff = new byte[1024];
        int len = inputStream.read(buff);
        log.info(new String(buff, 0, len));
    }

}
